package cn.com.shuyangyang;

import java.io.File;
import java.net.URL;
import java.security.ProtectionDomain;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.jetty.http.ssl.SslContextFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 启动jetty
 * 
 * @author shuYangYang
 * @email:shuyangyang@aliyun.com
 * @website:www.shuyangyang.com.cn
 */
public class MyServer {

	public static void main(String[] args) {
		Server server = new Server(80);
		startWar(server);
//		startWebApp(server);
	}

	/**
	 * War包启动方式
	 * 
	 * @param server
	 */
	@Autowired
	private static void startWar(Server server) {
		WebAppContext context = new WebAppContext();
		context.setServer(server);
		context.setContextPath("/"); // 项目起名

		ProtectionDomain protectionDomain = MyServer.class
				.getProtectionDomain();
		URL location = protectionDomain.getCodeSource().getLocation();
		String path = location.toExternalForm();
		try {
			File f = new File(location.toURI());
			String parent = f.getAbsolutePath();
			if (parent.endsWith(".jar")) parent = "jar:file:/" + parent + "!";
			path = parent + "/";
			System.out.println("#### using web root path:" + path);
			context.setWar(path);
			server.setHandler(context);
			// server = ConfigKeyStore(server,path);
			System.out.println("#### Begin....");

			server.start();
			DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
			System.out.println("#### Starting....");
			System.out.println("#### QuickStart Time: "
					+ format.format(new Date()));
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * SSL证书文件 CMD中输入：keytool -genkey -alias shuyangyangCA -keyalg RSA -keystore
	 * sm 根据提示输入相应的数据 导出证书：keytool -export -alias shuyangyangCA -file
	 * shuyangyang.cer -keystore sm -rfc
	 * 
	 * @param server
	 * @return
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	private static Server ConfigKeyStore(Server server, String path) {
		SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
		ssl_connector.setPort(8443);
		SslContextFactory cf = ssl_connector.getSslContextFactory();
		cf.setKeyStore(path + "sm");
		cf.setKeyStorePassword("shuyangyang");
		cf.setKeyManagerPassword("shuyangyang");
		server.addConnector(ssl_connector);
		return server;
	}
}
